import re
import os





def exec_jmeter(file, csv_file, threads=None, ramp_time=None, duration=None):
    '''
    :param file: 所要执行的jmeter脚本的路径
    :param threads:脚本需要设置的并发数
    :param time:脚本需要执行的时间
    :return: 返回脚本开始于结束时间戳
    '''
    # 修改 线程数
    if threads != None:
        with open(file, 'r+', encoding='utf-8') as F:
            content = F.read()

            content_threads = re.sub('<stringProp name="ThreadGroup.num_threads">(.*?)</stringProp>',
                                     '<stringProp name="ThreadGroup.num_threads">{}</stringProp>'.format(threads),
                                     content)
            with open(file, 'w+', encoding='utf-8') as F:
                F.writelines(content_threads)

    # 修改 线程启动时间
    if ramp_time != None:
        with open(file, 'r+', encoding='utf-8') as F:
            content = F.read()

            content_ramp = re.sub('<stringProp name="ThreadGroup.ramp_time">(.*?)</stringProp>',
                                  '<stringProp name="ThreadGroup.ramp_time">{}</stringProp>'.format(ramp_time),
                                  content)
            with open(file, 'w+', encoding='utf-8') as F:
                F.writelines(content_ramp)

    # 修改 执行时间
    if duration !=None:
        with open(file, 'r+', encoding='utf-8') as F:
            content = F.read()

            content_duration = re.sub('<stringProp name="ThreadGroup.duration">(.*?)</stringProp>',
                                      '<stringProp name="ThreadGroup.duration">{}</stringProp>'.format(duration),
                                      content)
            with open(file, 'w+', encoding='utf-8') as F:
                F.writelines(content_duration)

    # 命令行执行脚本并且设置测试数据存储路径
    command = os.popen('"D:\\apache-jmeter-5.1.1\\bin\jmeter" -n -t {} -l {}'.format(file, csv_file)).read()

    # 截取本次脚本执行时间段
    result = re.compile(r'\((.+?)\)').findall(command)
    start_time = int(int(result[0]) / 1000)
    end_time = int(int(result[-1]) / 1000)
    return [start_time,end_time]